package com.chang.bootplus.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.entity.Role;
import com.chang.bootplus.entity.RoleMenu;
import com.chang.bootplus.entity.UserRole;
import com.chang.bootplus.po.RoleMatchPO;
import com.chang.bootplus.po.RoleSelectPO;
import com.chang.bootplus.po.UserRolePO;
import com.chang.bootplus.service.RoleMenuService;
import com.chang.bootplus.service.RoleService;
import com.chang.bootplus.service.SchoolService;
import com.chang.bootplus.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = {"角色管理"})
@RequestMapping("/role")
@RestController
public class AdminRoleController {

    @Autowired
    SchoolService schoolService;


    @Autowired
    RoleMenuService roleMenuService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;




    @PostMapping("/infoRole")
    @ApiOperation(httpMethod = "POST", value = "获取角色详情")
    public ApiResponse<Void> infoRole(@RequestBody UserRolePO po){
        // 角色id-> 得到相关联的菜单id
        Role byId = roleService.getById(po.getId());
        List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, po.getId()));
        List<Long> menuIds = roleMenus.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
        byId.setMenuIds(menuIds);
        return new ApiResponse(byId);
    }


    @PostMapping("/selectRole")
    @ApiOperation(httpMethod = "POST", value = "角色列表查询")
    public ApiResponse<Void> addRole(@RequestBody RoleSelectPO po){
        Page<Role> rolePage = new Page<>(po.getPageNumber(), po.getPageSize());
        int count = roleService.count();
        Page<Role> page = roleService.page(rolePage, new LambdaQueryWrapper<Role>().like(Role::getRole, po.getName()).orderByDesc(Role::getGmtCreate));
        List<Role> roles = BeanUtil.listA2ListB(page.getRecords(), Role.class);
        return new ApiResponse(roles, page.getTotal(),new Long(count));
    }


    @PostMapping("/saveRole")
    @ApiOperation(httpMethod = "POST", value = "添加角色")
    public ApiResponse<Void> addRole(@RequestBody Role po){
        Role one = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getRole, po.getRole()));
        if (one!=null){
            throw new BusException("角色已存在");
        }

        roleService.save(po);
        return new ApiResponse().setReMsg("添加成功");
    }

    @PostMapping("/updateRole")
    @ApiOperation(httpMethod = "POST", value = "更新角色")
    public ApiResponse<Void> updateRole(@RequestBody Role po){
        //更新
        boolean b = roleService.updateById(po);
        // 更新角色编码
        // 更新缓存
        schoolService.clearUserAuthorityInfoByRoleId(po.getId());
        return new ApiResponse().setReMsg("更新成功");
    }

    /*
    *
    *
    *
    *
    * */

    @PostMapping("/deleteRole")
    @ApiOperation(httpMethod = "POST", value = "删除角色")
    public ApiResponse<Void> deleteRole(@RequestBody UserRolePO po){
        roleService.removeById(po.getId());
        // 删除中间表
        userRoleService.remove(new QueryWrapper<UserRole>().eq("role_id", po.getId()));
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", po.getId()));

        // 更新缓存
        schoolService.clearUserAuthorityInfoByRoleId(po.getId());
        return new ApiResponse().setReMsg("删除成功");
    }



    @Transactional
    @PostMapping("/premRole")
    @ApiOperation(httpMethod = "POST", value = "给角色分配权限")
    public ApiResponse<Void> matchRole(@RequestBody RoleMatchPO po){
        List<RoleMenu> sysRoleMenus = new ArrayList<>();

        Arrays.stream(po.getMenuIds()).forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(po.getRoleId());
            sysRoleMenus.add(roleMenu);
        });
        // 先删除原来的记录，再保存新的
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", po.getRoleId()));
        roleMenuService.saveBatch(sysRoleMenus);
        // 删除缓存
        schoolService.clearUserAuthorityInfoByRoleId(po.getRoleId());
        return new ApiResponse().setReMsg("授权成功");
    }


}
